package com.njupt.yanglonglong.report.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njupt.yanglonglong.report.demo.entity.DeviceApplied;
import com.njupt.yanglonglong.report.demo.service.DeviceAppliedService;
import com.njupt.yanglonglong.report.demo.mapper.DeviceAppliedMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 *
 */
@Service
public class DeviceAppliedServiceImpl extends ServiceImpl<DeviceAppliedMapper, DeviceApplied>
        implements DeviceAppliedService {

    @Autowired
    DeviceAppliedMapper deviceAppliedMapper;


    /**
     * 获得所有可选的设备（userId为空）
     *
     * @return
     */
    @Override
    public DeviceApplied getOptionalDivices() {
        QueryWrapper<DeviceApplied> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNull("user_id").or().eq("user_id", "");
        DeviceApplied deviceApplie = deviceAppliedMapper.selectOne(queryWrapper);
        return deviceApplie;
    }

    /**
     * 更新表，旨在存入userId表示占用
     *
     * @param userId
     * @param deviceApplied
     * @return
     */
    @Override
    public boolean onlineUser(String userId, DeviceApplied deviceApplied) {
        QueryWrapper<DeviceApplied> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        deviceApplied.setUserId(userId);
        int updateById = deviceAppliedMapper.updateById(deviceApplied);
        return updateById == 1;
    }

    /**
     * 使设备下线，用户置空
     *
     * @param deviceApplied
     * @return
     */
    @Override
    public boolean offlineUser(DeviceApplied deviceApplied) {
        deviceApplied.setUserId("");
        int update = deviceAppliedMapper.updateById(deviceApplied);
        return update == 1;
    }

    @Override
    public DeviceApplied getIsApplied(String userId) {
        QueryWrapper<DeviceApplied> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        DeviceApplied deviceApplied = deviceAppliedMapper.selectOne(queryWrapper);
        if (deviceApplied == null) {
            return null;
        }
        return deviceApplied;
    }
}




